package com.itheima.bos.web.action.base;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Actions;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;

import com.itheima.bos.bean.base.FixedArea;
import com.itheima.bos.service.FixedAreaService;

@Controller
@Namespace("/fixedArea")
@Actions
@ParentPackage("json-default")
@Scope("prototype")
public class FixedAreaAction extends BaseAction<FixedArea> {

	@Autowired
	private FixedAreaService service;

	@Action(value = "fixedArea_save", results = {
			@Result(name = "success", type = "redirect", location = "../pages/base/fixed_area.html") })
	public String save() {
		service.save(model);

		return SUCCESS;
	}

	@Action(value = "fixedArea_pageData", results = { @Result(name = "success", type = "json") })
	public String pageData(){
		Pageable pageAble = new PageRequest(page-1, rows);
		Specification<FixedArea> specification = new Specification<FixedArea>() {
			List<Predicate> list = new ArrayList<>();

			@Override
			public Predicate toPredicate(Root<FixedArea> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				Predicate predicate = null;
				if (StringUtils.isNoneBlank(model.getId())) {
					Predicate p = cb.equal(root.get("id").as(String.class), model.getId());
					list.add(p);
				}
				if (StringUtils.isNoneBlank(model.getCompany())) {
					Predicate p = cb.like(root.get("company").as(String.class), model.getCompany());
					list.add(p);
				}
				if (list.size() > 0 && list != null) {
					Predicate[] pp = new Predicate[list.size()];
					predicate = cb.and(list.toArray(pp));
				}
				return predicate;
			}

		}; 
		Page<FixedArea> pageData = service.findPageData(specification, pageAble);
		pushPageDataToValueStack(pageData);
		
		
		return SUCCESS;
	}

}
